package com.xiaowu.commons.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletRequest;

import org.apache.commons.lang3.Validate;

/**
 *  工具类
 * @author WH
 *
 */
public class Servlets {
	/**
	 * 取得带相同前缀的Request Parameters, copy from spring WebUtils.
	 * 
	 * 返回的结果的Parameter名已去除前缀.
	 */
	public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
		Validate.notNull(request, "Request must not be null");
		Enumeration paramNames = request.getParameterNames();
		Map<String, Object> params = new TreeMap<String, Object>();
		if (prefix == null) {
			prefix = "";
		}
		while ((paramNames != null) && paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				String unprefixed = paramName.substring(prefix.length());
				String[] values = request.getParameterValues(paramName);
				if ((values == null) || (values.length == 0)) {
				} else if (values.length > 1) {
					for (int i = 0; i < values.length; i++) {
						values[i] = values[i].trim();
					}
					params.put(unprefixed, values);
				} else {
					try {
						params.put(unprefixed, URLDecoder.decode(values[0].trim(),"UTF-8"));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						params.put(unprefixed, values[0].trim());
					}
				}
			}
		}
		return params;
	}
	public static Map<String, Object> getParameters(ServletRequest request) {
		return getParametersStartingWith(request, "");
	}
	
}
